<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>自定义别名脚本管理</title>
    <#include "/pubHeadStyle.html">
</head>
<body>
    <div class="bpmAuthorize tablesize roles" style="height:100%;padding:10px">
        <table id="aliasScript" lay-filter="aliasScript"></table>
    </div>
<!-- 三个及以上个 弹窗时启用的-->
<div id="windowUrls" style="display: none"></div>
<script type="text/html" id="aliasScriptBar">
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
    <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
    <a class="layui-btn layui-btn-xs" lay-event="detailed">明细</a>
    <a class="layui-btn layui-btn-xs" lay-event="help">帮助</a>
</script>
<script type="text/html" id="headerToolsBar">
    <div class="ccpui-enterSel">
        <div class="layui-btn-container">
            <a class="layui-btn layui-btn-sm" lay-event="query">
                <i class="layui-icon layui-icon-search"></i>
                <span>查询</span>
            </a>
            <a class="layui-btn layui-btn-sm" lay-event="add">
                <i class="layui-icon layui-icon-add-1"></i>
                <span>新增</span>
            </a>
            <a class="layui-btn layui-btn-sm" lay-event="edit">
                <i class="layui-icon layui-icon-edit"></i>
                <span>编辑</span>
            </a>
            <a class="layui-btn layui-btn-danger layui-btn-sm" lay-event="del">
                <i class="layui-icon layui-icon-delete"></i>
                <span>删除</span>
            </a>
            <a class="layui-btn layui-btn-sm" lay-event="export">
                <i class="layui-icon layui-icon-export"></i>
                <span>导出</span>
            </a>
            <a class="layui-btn layui-btn-sm" lay-event="import">
                <i class="layui-icon layui-icon-download-circle"></i>
                <span>导入</span>
            </a>
            <a class="layui-btn layui-btn-sm" lay-event="reset">
                <i class="layui-icon layui-icon-refresh"></i>
                <span>重置</span>
            </a>
        </div>
        <form class="layui-form" action="" lay-filter="queryForm" style="margin-top:10px">
            <div class="table-top-filter">
                <div class="table-filter-alone">
                    <label class="layui-form-label">脚本别名</label>
                    <input type="text" name="Q_aliasName_SL" class="layui-input filter-value" placeholder="脚本别名"/>
                </div>
                <div class="table-filter-alone">
                    <label class="layui-form-label">脚本描述</label>
                    <input type="text" name="Q_aliasDesc_SL" class="layui-input filter-value" placeholder="脚本描述"/>
                </div>
                <div class="table-filter-alone">
                    <label class="layui-form-label">脚本所在类名</label>
                    <input type="text" name="Q_className_SL" class="layui-input filter-value" placeholder="脚本所在类名"/>
                </div>
                <div class="table-filter-alone">
                    <label class="layui-form-label">调用方法</label>
                    <input type="text" name="Q_methodName_SL" class="layui-input filter-value" placeholder="调用方法"/>
                </div>
                <div class="table-filter-alone">
                    <label class="layui-form-label">脚本类型</label>
                    <select type="text" name="Q_scriptType_S" class="layui-input filter-value">
                        <option value="">全部</option>
                        <option value="default">系统默认</option>
                        <option value="custom">自定义</option>
                    </select>
                </div>
                <div class="table-filter-alone">
                    <label class="layui-form-label">是否启用</label>
                    <select type="text" name="Q_enable_L" class="layui-input filter-value">
                        <option value="">全部</option>
                        <option value="0">是</option>
                        <option value="1">否</option>
                    </select>
                </div>
            </div>
        </form>
    </div>
</script>

<script>
    layui.config({
        base: serverPath.systemPath + staticPath.systemPath //静态资源所在路径
    }).extend({
        index: 'index' //主入口模块
    }).use(['index','table','commons','layer','setter','common','totalFilter','admin','form','element'],function(){
        var table = layui.table;
        var $ = layui.$;
        var commons = layui.commons;
        var layer = layui.layer;
        var setter = layui.setter;
        var common = layui.common;
        var element = layui.element;
        var totalFilter = layui.totalFilter;
        var admin = layui.admin;
        var form = layui.form;

        var tableH = commons.tabHeight();

        loadTable(serverPath.workflowPath + setter.workflowLinkPath + 'aliasScript/list');

        function loadTable(url){
            table.render({
                elem: '#aliasScript'
                //, cellMinWidth: 80
                , title: '分管授权列表'
                , height: tableH
                , url: url
                , method: 'post'
                ,defaultToolbar: ['filter', 'print']
                , toolbar: '#headerToolsBar'
                , page: true
                , cols: [[
                    {type: 'checkbox'}
                    , {field: 'id', title: 'id', align: 'center',hide:true}
                    , {field: 'aliasName', title: '脚本别名', align: 'center',templet: function(d){
                            var html = '';
                            html += '<a href="javascript:void(0);" onclick=onAuthActClick("'+ d.id +'") style="color: blue;margin-right: 5px;">'+ d.aliasName +'</a>';
                            return html === '' ? '无' : html;
                        }}
                    , {field: 'aliasDesc', title: '脚本描述', align: 'center'}
                    , {field: 'className', title: '脚本所在类名', align: 'center'}
                    , {field: 'methodName', title: '调用方法', align: 'center'}
                    , {field: 'scriptType', title: '脚本类型', align: 'center',templet: function(d){
                            if (d.scriptType=='default') {
                                return '系统默认'
                            }else if (d.scriptType=='custom') {
                                return '自定义'
                            }else {
                                return '-'
                            }
                        }}
                    , {field: 'enable', width: 100, title: '是否启用', align: 'center',templet: function(d){
                            if (d.enable == 0){
                                return '<span style="color: green">是</span>'
                            }else {
                                return '<span style="color: red">否</span>'
                            }
                        }}
                    , { title: '管理', toolbar: '#aliasScriptBar', width: 150, align: 'center'}
                ]],done:function () {
                    common.tableSelectCon('.ccpui-enterSel .layui-form input','a[lay-event=query]','.ccpui-enterSel');
                }
            });
            totalFilter.init('aliasScript');
        }
        // 明细弹窗
        function detailedOpen(data){
            parent.layer.open({
                type: 2,
                title: '明细',
                area: ['1155px', '770px'],
                content: serverPath.workflowPath +  setter.workflowLinkPath + 'aliasScript/view/get?id='+data,
                skin: 'btn-class',
                btn: ['确定'],
                btnAlign: 'c',
            });
        }
        // 新增或修改弹窗
        function addOrUpdateHandle(type,data){
            parent.layer.open({
                type: 2,
                title: type === 'add' ? '新增' : '修改',
                area: ['1155px', '770px'],
                content: serverPath.workflowPath + setter.workflowLinkPath + 'aliasScript/view/edit' + (type === 'add' ?  '' : '?id='+data),
                skin: 'btn-class',
                btn: ['保存','取消'],
                btnAlign: 'c',
                yes: function(index,layero){
                    var form = layero.find('iframe').contents().find(".layui-form");
                    var aliasName =form.find("input[name=aliasName]").val();
                    if(aliasName==""){
                        parent.layer.msg("脚本名称不得为空，请输入", {time: 2500, icon: 5});
                        return ;
                    }
                    if(aliasName.length>80){
                        parent.layer.msg("脚本名称最多保存80位，请重新输入", {time: 2500, icon: 5});
                        return ;
                    }
                    //检查别名是否重复
                    $.ajax({
                        url: serverPath.workflowPath + setter.workflowLinkPath + 'aliasScript/checkRepeatName',
                        method: 'post',
                        dataType: 'json',
                        data: {
                            id: form.find("input[name=id]").val(),
                            aliasName: aliasName
                        },
                        success: function (data) {
                            if (data.code == 0) {
                                save(form, index);
                            } else {
                                parent.layer.msg(data.msg, {time: 2500, icon: 5});
                                return;
                            }
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            parent.layer.alert("保存失败！" + XMLHttpRequest.status);
                        }
                    });
                    return false;
                },
                btn2: function(index,layero){
                    parent.layer.close(index);
                }
            });
        }
        //保存接口
        function save(form,index){
            //新增判断：是不是系统默认的自定义脚本
            if (form.find("select[name=scriptType]").val()=="default") {
                var aliasScript = {};
                var isMethodNameIs;
                if (form.find("select[name=methodName]").val()){
                    aliasScript.methodName = form.find("select[name=methodName]").val().split("_")[0];
                    var data = JSON.parse(form.find("input[name=classNameData]").val());
                    $.each(data.data, function(key, val) {
                        if (aliasScript.methodName==val.methodName){
                            //1、判断参数个数是否相等
                            if( val.para.length!=form.find("div.layui-table-view tbody tr").length){
                                isMethodNameIs = false;
                            }else {
                                //2、一一对比参数类型是否相同
                                $(val.para).each(function (index,row) {
                                    //只要有一个参数类型不同就返回false
                                    if(row.paraType!=form.find("div.layui-table-view tbody tr").eq(index).find("td").eq(1).text()){
                                        isMethodNameIs = false;
                                    }else {
                                        //只有参数个数相同，类型也一一对应才返回true
                                        isMethodNameIs = true;
                                    };
                                });
                            }
                            if (isMethodNameIs){
                                aliasScript.argument=val.para;
                                aliasScript.paraDesc=[];
                                $.each(aliasScript.argument,function (k,v) {
                                    if (aliasScript.argument.length>1){
                                        aliasScript.paraDesc.push(form.find("input[name=paraDesc]").eq(k).val());
                                    }else {
                                        aliasScript.paraDesc;
                                        aliasScript.paraDesc=form.find("input[name=paraDesc]").eq(k).val();
                                    }
                                    aliasScript.argument[k].paraDesc=form.find("input[name=paraDesc]").eq(k).val();

                                    if (form.find("input[name=isRequired]").eq(k).prop("checked")) {
                                        // do something
                                        aliasScript.argument[k].isRequired=1;
                                    }else {
                                        aliasScript.argument[k].isRequired=0;
                                    }

                                })
                            }
                        }
                    });
                }
            }else{
                //自定义脚本时检查是否使用双引号，防止回显报错
                if( form.find("textarea[name=scriptComten]").val().indexOf('"') != -1 ){
                    parent.layer.msg("脚本内容中请用单引号代替双引号", {time: 2500, icon:0});
                    return;
                }
            }

            $.ajax({
                url: serverPath.workflowPath + setter.workflowLinkPath + 'aliasScript/save',
                method: 'post',
                dataType: 'json',
                data:{
                    id:form.find("input[name=id]").val(),
                    aliasName:form.find("input[name=aliasName]").val(),
                    aliasDesc:form.find("input[name=aliasDesc]").val(),
                    scriptType:form.find("select[name=scriptType]").val(),
                    className:form.find("select[name=className]").val(),
                    classInsName:form.find("input[name=classInsName]").val(),
                    methodName:aliasScript==undefined?null:aliasScript.methodName,
                    methodDesc:form.find("input[name=methodDesc]").val(),
                    returnType:form.find("input[name=returnType]").val(),
                    argument:aliasScript==undefined?null:JSON.stringify(aliasScript.argument),
                    enable:form.find("select[name=enable]").val(),
                    scriptComten:form.find("textarea[name=scriptComten]").val()
                },
                success: function(data){
                    if (data.code==0){
                        parent.layer.msg(data.msg,{time: 2500, icon:6});
                        parent.layer.close(index);
                        table.reload('aliasScript',{page: {curr: 1}});
                    }else {
                        parent.layer.msg(data.msg,{time: 2500, icon:5});
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    parent.layer.alert("保存失败！" + XMLHttpRequest.status);
                }
            });};
        //监听工具条
        table.on('tool(aliasScript)', function(obj){ //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
            var data = obj.data; //获得当前行数据
            var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
            var tr = obj.tr; //获得当前行 tr 的 DOM 对象（如果有的话）
            if(layEvent === 'edit'){ //编辑
                addOrUpdateHandle('edit',data.id);
                //do somehing
            } else if(layEvent === 'del'){ //删除
                layer.confirm('确认删除吗?', function(index){
                    obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
                    layer.close(index);
                    //向服务端发送删除指令
                    $.ajax({
                        url: serverPath.workflowPath + setter.workflowLinkPath + 'aliasScript/del',
                        type: 'post',
                        dataType: 'json',
                        data: {
                            ids: data.id.toString()
                        },
                        success: function(data){
                            if(data.code !== 0){
                                layer.msg(data.msg, {time: 2500, icon:5});
                                return false;
                            }
                            layer.msg(data.msg, {time: 500, icon:6});
                            table.reload('aliasScript',{page: {curr: 1}});
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            layer.alert("删除失败！" + XMLHttpRequest.status);
                        }
                    });
                });
            } else if(layEvent === 'detailed'){ //明细
                //do something
                detailedOpen(data.id);

            } else if(layEvent === 'preview'){ //预览
                //do something
                var str = '';
                var alias ='';
                if(obj.data.argument!==''){
                    alias =JSON.parse(obj.data.argument);
                    $.each(JSON.parse(obj.data.argument),function (k,v) {
                        str += ','+v.paraName;
                    })
                }

                if (str!=''){
                    str = str.substr(1);
                }
                var scriptStr = obj.data.classInsName+'.'+obj.data.methodName+'('+str+')';
                var aliasStr = '';
                $.each(alias,function (k,v) {
                    aliasStr += ','+JSON.stringify(v).replace("\"", "%22").replace("{", "%7b").replace("}", "%7d").replace("[", "").replace("]", "");
                });
                if (aliasStr!=''){
                    aliasStr = aliasStr.substr(1);
                }
                var windowUrl =serverPath.workflowPath+setter.workflowLinkPath+'aliasScript/view/toPreview?scriptStr='+scriptStr+'&alias='+aliasStr;
                $('#windowUrls').load(windowUrl,{},function(response,status,xhr){
                    layer.open({
                        title:'预览',
                        type: 1,
                        area: ['80%', '90%'],
                        skin: 'btn-class',
                        btn : [ "预览", "关闭" ],
                        content: $('#windowUrls'),
                        success:function (layero,index) {
                            //第一个实例
                            table.render({
                                elem: '#aliasTable'
                                ,id:'aliasTable'
                                ,data: alias
                                ,page: false //开启分页
                                ,cols: [[ //表头
                                    {field: 'paraName', title: '参数名'}
                                    ,{field: 'paraType', title: '参数类型', sort: true}
                                    ,{
                                        field: 'paraValue',
                                        title: '参数值',
                                        templet: function(d){
                                            return '<input type="text" name="paraValue" value="" lay-filter="paraValue" placeholder="请输入" class="layui-input">'
                                        }
                                    }
                                ]]
                                ,done:function () {
                                }
                            });
                        },
                        yes:function (index,layero) {
                            $('#resultView').text('');
                            if ($('input[name=paraValue]').eq(0).val()==""){
                                layer.msg("请输入有效参数!",{icon:0});
                                return false;
                            }
                            $.each(alias,function (k,v) {
                                alias[k].paraValue = $('input[name=paraValue]').eq(k).val();
                                delete alias[k].LAY_TABLE_INDEX;
                                delete alias[k].paraDesc;
                            })
                            $.ajax({
                                type: 'POST',
                                url: serverPath.workflowPath + setter.workflowLinkPath + "aliasScript/preview",
                                data: {
                                    scriptStr: scriptStr,
                                    alias:JSON.stringify(alias)
                                },
                                success: function (res) {
                                    if (res.code==0) {
                                        layer.msg("查询成功!",{icon:1});
                                        $('#resultView').text(JSON.stringify(res.data));
                                    }else {
                                        layer.msg("查询失败!",{icon:2});
                                    }
                                },
                                dataType: 'json'});

                        }
                    });
                });
            } else if(layEvent === 'help'){
                parent.layer.open({
                    type: 2,
                    title: '帮助',
                    area: ['1155px', '770px'],
                    content: serverPath.workflowPath + setter.workflowLinkPath + 'aliasScript/view/help',
                    skin: 'btn-class',
                    btn: ['确定'],
                    btnAlign: 'c'
                });
            }
        });
        // 监听头工具栏事件
        table.on('toolbar(aliasScript)',function(obj){
            var checkStatus = table.checkStatus(obj.config.id);
            var data = checkStatus.data; //获取选中行数据
            switch (obj.event) {
                case 'query':
                    common.tableConditionRender("aliasScript","queryForm",{where:{}},false);
                    break;
                case 'add':
                    addOrUpdateHandle('add');
                    break;
                case 'edit':
                    if(data.length !== 1){
                        layer.msg("请选择一项数据!", {time: 2500, icon:5});
                        return false;
                    }
                    addOrUpdateHandle('edit',data[0].id);
                    break;
                case 'del':
                    if(data.length === 0){
                        layer.msg("请选择一项数据!", {time: 2500, icon:5});
                        return false;
                    }
                    var ids = $.map(data,function(v){
                        return v.id;
                    });
                    layer.confirm("确认删除吗?",{icon:0},function(index){
                        layer.close(index);
                        $.ajax({
                            url: serverPath.workflowPath + setter.workflowLinkPath + 'aliasScript/del',
                            type: 'post',
                            dataType: 'json',
                            data: {
                                ids: ids.toString()
                            },
                            success: function(data){
                                if(data.code !== 0){
                                    layer.msg(data.msg, {time: 2500, icon:5});
                                    return false;
                                }
                                layer.msg(data.msg, {time: 500, icon:6});
                                table.reload('aliasScript',{page: {curr: 1}});
                            },
                            error: function (XMLHttpRequest, textStatus, errorThrown) {
                                layer.alert("删除失败！" + XMLHttpRequest.status);
                            }
                        });
                    });
                    break;
                case 'export':
                    if (data.length == 0) {
                        layer.confirm('还没有选择，是否导出全部？', {
                            btn: ['确定', '取消'] //按钮
                        }, function (index) {
                            layer.close(index);
                            var url = serverPath.workflowPath + setter.workflowLinkPath + 'aliasScript/exportXml';
                            window.location.href = url;
                        });
                    } else {
                        layer.confirm('确定导出吗？', {
                            btn: ['确定', '取消'] //按钮
                        }, function (index) {
                            layer.close(index);
                            var ids = [];
                            for (var i = 0; i < data.length; i++) {
                                ids.push(data[i].id);
                            }
                            var tableIds = ids.join(',');
                            var url = serverPath.workflowPath + setter.workflowLinkPath + 'aliasScript/exportXml?tableIds=' + tableIds;
                            window.location.href = url;
                        });
                    }
                    break;
                case 'import':
                    var iframeWin;
                    layer.open({
                        type: 2,
                        title: "导入",
                        shade: 0.3,
                        area: ['400px', '300px'],
                        content: serverPath.workflowPath + setter.workflowLinkPath + "aliasScript/view/importXml",
                        success: function(layero, index){
                            iframeWin = window[layero.find('iframe')[0]['name']];
                        },
                        end: function(){
                            if(iframeWin.layui.needReload!=undefined){
                                table.reload('aliasScript',{page: {curr: 1}});
                            }
                        }
                    });
                    break;
                case 'reset':
                    common.tableConditionRender("aliasScript","queryForm",{where:{}},true);
                    break;
            }
        });
        // 点击流程名称弹窗
        window.onAuthActClick = function(defKey){
            detailedOpen(defKey);
        }
    });
</script>
<style>
    .layui-table-tool-self {
        display: none;
    }
    .bpmAuthorize .table-top-filter div input {
        border-radius: 4px;
        float: left;
        width: 170px;
    }
    .bpmAuthorize .table-top-filter label.layui-form-label {
        width: 114px !important;
        float: left;
    }
</style>
</body>
</html>